const { set } = require("mongoose")

module.exports = async function () {
    const ws = require("nodejs-websocket")
    const chatDB = require("../routes/chats")
    console.log("聊天服务启动中。。。")
    //在线用户列表池
    let con = []

    let server = ws.createServer(conn => {
        console.log("新的连接")
        conn.on("close", () => {
            console.log("连接已断开")
            con.forEach((item, idx) => {
                if (item.conn == conn) {
                    con.splice(idx, 1)
                }
            })
        })
        conn.on("text", async (data) => {
            data = JSON.parse(data)
            console.log(data)
            let temp = false
            let mark = data.user + data.company
            //检测新的连接是否是新用户
            if (con.length == 0) {
                let cons = {
                    mark: mark,
                    conn: conn
                }
                con.push(cons)
            } else {
                con.forEach((item) => {
                    if (item.conn != conn) {
                        temp = true
                    }
                })
            }
            //如果没有当前连接，则推入新的连接到连接池
            if (temp) {
                let cons = {
                    mark: mark,
                    conn: conn
                }
                con.push(cons)
            }
            console.log(mark)
            // console.log(con)
            //根据mark选择连接对象
            let se = []
            con.forEach((item) => {
                if (item.mark == mark) {
                    se.push(item)
                }
            })
            let finddata = {
                mark: mark,
                msg: {
                    msg: data.msg,
                    sender: data.sender
                }
            }
            let dbdata = await chatDB(finddata)
            console.log("数据库返回结果：", dbdata)
            // @ts-ignore
            dbdata = JSON.stringify(dbdata)
            sendmsg(se, dbdata)
        })
    }, (e) => {
        console.log(e)
    }).listen(8000)
    function sendmsg(se, msg) {
        console.log("已有的连接：", con)
        console.log("发送的连接：", se)
        se.forEach((item) => {
            if (item.conn.readyState != 1) return;
            item.conn.sendText(msg)
            console.log("返回：", msg)
        })
    }
    console.log("聊天服务启动完成！！！")
}